var util = require('../../utils/util.js');
Page( {
  data: {
    orderList: [],
    user: null
  },

  onLoad: function(e) {
    var user = wx.getStorageSync('user');
    if (user == '' || user.uid == '') {
      wx.showModal({ content: '数据加载失败，请重新进入！', showCancel: false });
      return;
    }
    this.setData({ user: user });
    // 获取订单列表
    this.getOrderList();
  },

  submit: function(e) {
    var idx = e.currentTarget.dataset.idx;
    var orderList = this.data.orderList;
    var order = orderList[idx];
    if (order.addressId == null || order.addressId == null || order.addressId == '') {
      wx.showModal({ content: '请添加一个收货地址！', showCancel: false });
      return;
    }
    var submitType = e.currentTarget.dataset.type;
    // 设置当前订单
    order.payed = true;
    order["appId"] = 'wx0b236a02a79e42f7';
    orderList[idx] = order;
    this.setData({ orderList: orderList });
    
    // 取消订单
    if (submitType == 'cancel') {
      this.cancelOrder(order);
      return;
    }
    // 修改并发起支付
    if (order != null) {
      console.log('现在支付', order);
      wx.request({
        url: util.requestUrl.payAgain,
        method: 'POST',
        data: order,
        header: { 'content-type': 'application/json' },
        success: res => {
          console.log('res', res);
          if (res.data.success) {
            if (res.data.payment == null || res.data.payment.paySign == null) {
              wx.showModal({ content: '支付出错了，请退出重试！', showCancel: false });
              return;
            }
            this.wxpay(res.data.payment, idx);
          }
        },
        fail: res => {
          order.payed = false;
          orderList[idx] = order;
          this.setData({ orderList: orderList });
        }
      });
    }
  },

  wxpay: function (result, idx) {
    var orderList = this.data.orderList;
    var order = orderList[idx];
    // 调起支付
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: result.package,
      signType: result.signType,
      paySign: result.paySign,
      success: res => {
        // 成功则弹出输入密码
        console.log('success', res);
        if (res.errMsg == 'requestPayment:ok') {
          wx.showModal({ content: '支付成功，商家将在48小时内为您发货！', showCancel: false });
          this.getOrderList();
        }
      },
      fail: res => {
        console.log('用户取消支付');
        order.payed = false;
        orderList[idx] = order;
        // 设置按钮可点击
        this.setData({ orderList: orderList });
      },
      complete: res => {
        console.log('complete', res);
        // 取消支付
        if (res.errMsg == 'requestPayment:fail cancel') {
          order.payed = false;
          orderList[idx] = order;
          // 设置按钮可点击
          this.setData({ orderList: orderList });
        }
      }
    });
  },

  /**
   * 购买数量加减操作
   */
  buyNum: function (e) {
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var orderList = this.data.orderList;
    var buyNum = parseInt(orderList[id].count);
    if (type == -1 && buyNum == 1) return;
    buyNum = (type == -1 && buyNum > 1) ? (buyNum - 1) : (buyNum + 1);
    orderList[id].count = buyNum;
    this.setorderList(orderList);
  },

  // 输入数量
  inputNum: function (e) {
    var num = e.detail.value;
    if (isNaN(num) || num <= 0) return;
    var id = e.currentTarget.dataset.id;
    var orderList = this.data.orderList;
    orderList[id].count = num;
    this.setorderList(orderList);
  },

  /**
   * 设置购物车数据
   */
  setorderList: function (orderList) {
    for (var i = 0; i < orderList.length; i++) {
      var totalPrice = orderList[i].price * orderList[i].count;
      orderList[i].totalPrice = totalPrice.toFixed(2);
    }
    this.setData({ orderList: orderList });
  },

  getOrderList: function() {
    wx.request({
      url: util.requestUrl.orderList,
      method: 'GET',
      data: { "uid": this.data.user.uid },
      header: { 'content-type': 'application/json' },
      success: res => {
        var result = res.data;
        if (result.success) {
          if (result.list.length > 0) {
            this.setData({ orderList: result.list });
          }
        }
      }
    })
  },

  // 点击进入选择/新增地址
  editAddress: function(e) {
    var idx = e.currentTarget.dataset.idx;
    var order = this.data.orderList[idx];
    if (order.payStatus != 0 && order.payStatus != 2) {
      wx.showModal({ content: '当前订单状态不允许修改哦！', showCancel: false });
      return;
    }
    wx.chooseAddress({
      success: res => {
        this.saveAddress(res, idx);
      },
      fail: function(res) {
        console.log('fail', res);
      }
    });
  },

  saveAddress: function (formData, idx) {
    console.log('formData', formData);
    if (formData.provinceName.indexOf('新疆') > -1
     || formData.provinceName.indexOf('西藏') > -1
     || formData.provinceName.indexOf('内蒙古') > -1) {
      wx.showModal({ content: '抱歉，暂不支持该地址配送！', showCancel: false });
      return;
    }
    var address = {
      "uid": this.data.user.uid,
      "phone": formData.telNumber,
      "name": formData.userName,
      "address": formData.provinceName + formData.cityName + formData.countyName + formData.detailInfo,
      "flag": 1
    }
    wx.request({
      url: util.requestUrl.addressSave,
      method: 'POST',
      data: address,
      header: { 'content-type': 'application/json' },
      success: res => {
        console.log('res', res);
        if (res.data.success) {
          var orderList = this.data.orderList;
          var order = orderList[idx];
          // 设置地址
          order.address = address;
          order.addressId = res.data.addressId;
          this.setData({ orderList: orderList });
          console.log('保存新地址', orderList);
        }
      }
    });
  },

  cancelOrder: function (order) {
    wx.request({
      url: util.requestUrl.orderCancle,
      method: 'POST',
      data: order,
      header: { 'content-type': 'application/json' },
      success: function (res) {
        console.log('res', res);
        if (res.data.success) {
          wx.showModal({ content: '订单取消成功！', showCancel: false });
        }
      },
      fail: function (res) {
        console.log('fail', res);
      }
    });
  },

  queryExpress: function(e) {
    wx.navigateTo({ 
      url: '/pages/express/express?postid=' + e.currentTarget.dataset.postid + '&type=' + e.currentTarget.dataset.type
    });
  }

})
